﻿Imports SACommon
Public Class frmMain
    Dim mMenu As Menus
    Dim uc As Control
    Dim p As ProgressWaitForm

    Private mUpdating As Boolean
    Private mSuccess As Boolean
    Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
        'Initialise variables
        UpdateCore.VersionFile = "Update.html"
        UpdateOption.LoadOptions()

        gCat = New Category
        gUDApp = New UpdateApp
        gSettings = New StartupSettings()

        lblVersion.Text = Application.ProductVersion
        lblMessage.Text = ""
        SetFormTitle()

        'Create the main menu
        LoadMenu()

        'ShowHomeScreen()
        OpenInfoPage()
    End Sub
    Private Sub frmMain_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        lvwMenu.Focus()

        'Register the listeners
        AddHandler UpdateCore.InternetConnectionStateChanged, AddressOf ReportConnectionState
        AddHandler Messenger.MessengerMessage, AddressOf OnTaskMessage
        AddHandler gUDApp.ApplicationStatusChanged, AddressOf UpdateApplicationStatus

        'Check for system updates
        If UpdateCore.Connected(True) = False Then ShowMessage("Application is not connected to the internet. Please connect before continuing!")
        CheckForUpdates()
    End Sub

#Region "Connection State"
    Sub ReportConnectionState(Connected As Boolean)
        If CBool(Connected) = False Then
            pbConnected.Image = My.Resources.link_network_delete2
            ttMain.SetToolTip(pbConnected, "Not connected to the internet")
        Else
            pbConnected.Image = My.Resources.link_network_ok2
            ttMain.SetToolTip(pbConnected, "Connected to the internet")
        End If
    End Sub
#End Region
#Region "Message Notifier"
    Sub OnTaskMessage(MessageType As Messenger.MessageType, MessageContent As Messenger.MessageContent)
        Dim tContent As String = MessageContent.Message
        Dim tSuccess As Boolean = MessageContent.Success

        Select Case MessageType
            Case Is = Messenger.MessageType.AppSelected
                ShowMessage(gUDApp.SelectedApp.ApplicationTitle & " > selected")
                SetFormTitle()
                LoadMenu()
                OpenApplicationPage()

            Case Is = Messenger.MessageType.ChangePage
                Select Case tContent
                    Case Is = "Version"
                        OpenVersionPage()
                End Select

            Case Is = Messenger.MessageType.AppUpdated
                ShowMessage(gUDApp.SelectedApp.ApplicationTitle & " > selected")
                ShowHomeScreen()

            Case Is = Messenger.MessageType.CategoryEdit
                OpenCategoriesPage()

            Case Is = Messenger.MessageType.UpdateStart
                ShowMessage(tContent)
                Me.Enabled = False

            Case Is = Messenger.MessageType.UpdateEnd
                ShowMessage(tContent)
                Me.Enabled = True

            Case Is = Messenger.MessageType.GeneralMessage
                ShowMessage(tContent)

            Case Is = Messenger.MessageType.WaitformOpen
                p = ProgressWaitForm.ShowProgress(Me)

            Case Is = Messenger.MessageType.WaitFormMessage
                p.UpdateProgress(tContent)

            Case Is = Messenger.MessageType.WaitFormClose
                p.CloseProgress()

        End Select
    End Sub
#End Region
#Region "Process Menu"
    Private Sub lvwMenu_Click(sender As Object, e As EventArgs) Handles lvwMenu.Click
        ShowMessage("")
        If lvwMenu.SelectedItems.Count > 0 Then
            ProcessMenu(lvwMenu.SelectedItems(0).Tag)
        End If
    End Sub
    Sub ProcessMenu(Options As String)
        If UpdateCore.Connected(False) = False Then Exit Sub
        Select Case Options
            Case Is = AppHome
                gUDApp.SelectedAppID = 0
                LoadMenu()
                SetFormTitle()
                ShowHomeScreen()

            Case Is = AppNew
                gUDApp.SelectedAppID = 0
                OpenApplicationPage()

            Case Is = AppEdit
                OpenApplicationPage()

            Case Is = AppDelete
                DeleteApplication()

            Case Is = AppExit
                CloseProgramme()

            Case Is = FilMan
                gAppFile = New AppFile
                OpenFilesPage()

            Case Is = FilCln
                gAppFile = New AppFile
                CleanFTP()

            Case Is = VerMan
                OpenVersionPage()

            Case Is = SetMan
                OpenSettingsPage()

            Case Is = AppInfo
                OpenInfoPage()

            Case Is = AppLib
                OpenLibraryPage()
        End Select
    End Sub
    Sub LoadMenu()
        'Reset menu
        lvwMenu.Groups.Clear()
        lvwMenu.Items.Clear()
        mMenu = New Menus()
        'Add items
        For Each citem In mMenu.CategoryList
            lvwMenu.Groups.Add(citem.Category)
            For Each mitem In citem.Items
                lvwMenu.Items.Add(mitem)
            Next
        Next
    End Sub
#End Region
#Region "Do Updates"
    Sub CheckForUpdates()
        Dim tinstallerVersion As String = gSettings.GetValue(StartupSettings.SettingsValue.InstallerVersion)

        saUC.VersionFile = "Update.html"
        saUC.RepositoryServer = "http://sanguinesw.azurewebsites.net"
        saUC.RepositoryFolder = "/software/SAUpdater"
        saUC.CurrentApplicationVersion = Application.ProductVersion
        saUC.CurrentInstallerVersion = tinstallerVersion
        saUC.AutoCheck = False

        If saUC.CheckUpdate() = True Then
            If saUC.HasInstallerUpdate = True Then
                Messenger.SendMessage(Messenger.MessageType.WaitformOpen, "Downloading Installer", True)
                ShowMessage("Downloading Installer " & saUC.NewInstallerVersion)
                mUpdating = True
                AddHandler saUC.InstallerDownloadProgress, AddressOf InstallerUpdateProgress
                AddHandler saUC.InstallerDownloadCompleted, AddressOf InstallerUpdateCompleted
                saUC.DoInstallerUpdate()
                Do
                    Application.DoEvents()
                Loop Until mUpdating = False
                If mSuccess = True Then gSettings.Add(StartupSettings.SettingsValue.InstallerVersion, saUC.NewInstallerVersion)
                gSettings.Save()
                RemoveHandler saUC.InstallerDownloadProgress, AddressOf InstallerUpdateProgress
                RemoveHandler saUC.InstallerDownloadCompleted, AddressOf InstallerUpdateCompleted
                Messenger.SendMessage(Messenger.MessageType.WaitFormClose, "", True)
                ShowMessage("Installer sucessfully updated")
            End If

            gApp.UpdateAvailable = saUC.HasApplicationUpdate
        Else
            gApp.UpdateAvailable = False
            ShowMessage(saUC.ErrorMessage.Message)
        End If
    End Sub
    Public Sub InstallerUpdateProgress(Percentage As Integer)
        Dim tString As String = String.Format("{0}% Downloaded", Percentage)
        Messenger.SendMessage(Messenger.MessageType.WaitFormMessage, tString, True)
        MyInvoke.CustomInvoke(lblMessage, Function(f) f.Text = (Percentage & "% Downloaded").ToString)
        Application.DoEvents()
    End Sub
    Public Sub InstallerUpdateCompleted(Success As Boolean)
        mSuccess = Success
        mUpdating = False
    End Sub
#End Region
#Region "General Functions"
    Sub ShowMessage(Message As String)
        lblMessage.Text = Message
        Application.DoEvents()
    End Sub
    Sub SetFormTitle()
        Me.Text = "SA Updater"
        If gUDApp.SelectedApp.ApplicationTitle.Trim <> "" Then Me.Text &= " > " & gUDApp.SelectedApp.ApplicationTitle
    End Sub
    Sub UpdateApplicationStatus()
        LoadMenu()
    End Sub
    Sub ShowControl()
        ClientPanel.Controls.Clear()
        uc.Dock = DockStyle.Fill
        ClientPanel.Controls.Add(uc)
        uc.BringToFront()
    End Sub
    Sub ShowHomeScreen()
        uc = New ucStart
        ShowControl()
    End Sub
    Sub CloseProgramme()
        If MessageBox.Show("Are you sure you want to exit?", "Exit Application", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then Me.Close()
    End Sub
    Sub OpenInfoPage()
        uc = New ucAbout
        ShowControl()
    End Sub
    Sub OpenLibraryPage()
        uc = New ucLibrary
        ShowControl()
    End Sub
#End Region
#Region "Applications"
    Sub OpenApplicationPage()
        uc = New ucApplication()
        ShowControl()
    End Sub
    Sub DeleteApplication()
        If gUDApp.SelectedAppID <> 0 Then
        Else
            ShowMessage("Please select an application first!")
        End If
    End Sub
#End Region
#Region "Categories"
    Sub OpenCategoriesPage()
        uc = New ucCategory()
        ShowControl()
    End Sub
#End Region
#Region "Files"
    Sub OpenFilesPage()
        uc = New ucFiles()
        ShowControl()
    End Sub
    Sub CleanFTP()
        uc = New ucCleanFTP
        ShowControl()
    End Sub
#End Region
#Region "Version"
    Sub OpenVersionPage()
        gVersion = New Version
        gAppFile = New AppFile
        uc = New ucVersion
        ShowControl()
    End Sub
#End Region
#Region "Settings"
    Sub OpenSettingsPage()
        uc = New ucSettings
        ShowControl()
    End Sub
#End Region
End Class